
package jogs.games.bs;

import jogs.core.*;
import jogs.games.Game;
import jogs.games.Card;
import java.io.Serializable;
import java.util.*;

public class BS extends Game 
{
  private GameServer parent; 
  private boolean started = false; 
  private ArrayList<Player> turnOrder;
  private int turnIndex; 
  private Player turnPlayer = null;

  private ArrayList<Card> deck; 
  private HashMap<Player, ArrayList<Card>> playerHands; 

  public BS(String name, GameServer _parent, int maxPlayers)
  {
    gameName = name; 
    parent = _parent; 
    maxPlayers = this.maxPlayers;
  }

  private String encodeHands(Player focusPlayer)
  {
    String info = "";

    for (Player p : playerHands.keySet())
    {
      ArrayList<Card> hand = playerHands.get(p); 

      if (p == focusPlayer)
      {
        String list = ""; 
        for (Card c : hand)
          list += (c.toString() + ","); 
        list = Helpers.chomp(list); 

        info += (list + ";"); 
      }
      else
      {
        info += (p.getName() + "=" + hand.size() + ";"); 
      }
    }

    info = Helpers.chomp(info); 

    return info;    
  }
  

  private void startGame() 
  {
    // setup the game
    turnOrder = new ArrayList<Player>(); 
    turnOrder.addAll(parent.getPlayers()); 
    Collections.shuffle(turnOrder); 

    deck = Card.newDeck(); 

    playerHands = new HashMap<Player, ArrayList<Card>>(); 
    for (int i = 0; i < turnOrder.size(); i++)
      playerHands.put(turnOrder.get(i), new ArrayList<Card>()); 

    int pindex = 0; 
    while (deck.size() > 0)
    {
      Card c = deck.remove(0); 
      ArrayList<Card> hand = playerHands.get(turnOrder.get(pindex)); 
      hand.add(c); 
      pindex = (pindex + 1) % turnOrder.size(); 
    }

    // send everyone an @START with some info
    for (Player p : playerHands.keySet())
    {
      String info = encodeHands(p); 
      p.send("@START:" + info); 
    }
    
    // send first player an @TURN
    turnIndex = 0; 
    turnPlayer = turnOrder.get(turnIndex); 
    turnPlayer.send("@TURN:"); 


    started = true; 
  }

	public void chat(String message, Player p)
  {
  }
	
	public void move(Player p, String move)
  {
    //System.out.println("Got move from " + p.getPlayerName() + ": " + move); 
    if (move.equals("start") && !started)
      startGame(); 
  }
	
	public String getStatus()
  {
    return "BS," + gameName;
  }
	
	public int getNumPlayers()
  {
    return 0; 
  }
	
	public boolean join(Player p)
  {
    return false; 
  }
	
	public void leave(Player p)
  {
  }
	
	public void close()
  {
  }
	
}

